package com.echo.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;

import com.echo.adapter.MusicAdapter;
import com.echo.model.Music;
import com.echo.service.MusicService;
import com.echo.util.DrawableUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MusicActivity extends AppCompatActivity {

    private RecyclerView mMusicRecycler;
    private MusicAdapter mAdapter;
    private List<Music> mMusics;
    private Toolbar mToolbar;
    private TextView mToobarTitle;
    private MusicService mService;
    private boolean mBind=false;
    private SeekBar mProgress;
    private TextView mSongTitle;
    private ImageView mPlayPauseButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);

        initActionBar();

        mMusics=getMusics(this);

        mProgress= (SeekBar) findViewById(R.id.song_progress_bar);
        mProgress.setMax(100);
        mSongTitle= (TextView) findViewById(R.id.song_title_text);
        mPlayPauseButton= (ImageView) findViewById(R.id.play_pause);
        mPlayPauseButton.setSelected(false);
        mMusicRecycler= (RecyclerView) findViewById(R.id.music_recycler);
        mMusicRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));
        mAdapter=new MusicAdapter(this,mMusics);
        mMusicRecycler.setAdapter(mAdapter);

        Intent intent=new Intent(MusicActivity.this, MusicService.class);
        bindService(intent,conn,Context.BIND_AUTO_CREATE);
    }

    private void initActionBar() {
        mToolbar = (Toolbar) findViewById(R.id.music_toolbar);
        mToobarTitle = (TextView) findViewById(R.id.music_toolbar_title);
        mToobarTitle.setText("音乐");
        mToobarTitle.setTextColor(Color.parseColor("#8a041835"));
        mToolbar.setTitle("");
        mToolbar.setNavigationIcon(
                DrawableUtil.tintDrawable(getResources()
                        .getDrawable(R.mipmap.ic_arrow_back_black_36dp),Color.parseColor("#8a041835")));
        setSupportActionBar(mToolbar);
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            mBind=false;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
            mService = binder.getService();
            mBind=true;
            mService.setOnProgressListener(new MusicService.OnProgressListener() {
                @Override
                public void onProgress(int progress) {
                    mProgress.setProgress(progress);
                }
            });
            mService.setOnMusicChangeListener(new MusicService.OnMusicChangeListener() {
                @Override
                public void onMusicChange(String name) {
                    mSongTitle.setText(name);
                    mProgress.setProgress(0);
                }
            });
        }
    };

    public void play_pause(View view) throws IOException {
        if(mBind){
            mService.play();
            if(mPlayPauseButton.isSelected()) {
                mPlayPauseButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_play_arrow_black_36dp));
                mPlayPauseButton.setSelected(false);
            }
            else {
                mPlayPauseButton.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_pause_black_48dp));
                mPlayPauseButton.setSelected(true);
            }
        }
    }

    public void next(View view) throws IOException {
        if(mBind){
            mService.next();
        }
    }

    public void previous(View view) throws IOException {
        if(mBind){
            mService.pre();
        }
    }



    public static List<Music> getMusics(Context context) {
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        List<Music> musics = new ArrayList<Music>();
        for (int i = 0; i < cursor.getCount(); i++) {
            Music music = new Music();
            cursor.moveToNext();
            long id = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media._ID)); // 音乐id
            String title = cursor.getString((cursor
                    .getColumnIndex(MediaStore.Audio.Media.TITLE)));// 音乐标题
            String artist = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Audio.Media.ARTIST));// 艺术家
            long duration = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DURATION));// 时长
            long size = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media.SIZE)); // 文件大小
            String url = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DATA)); // 文件路径
            int isMusic = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));// 是否为音乐
            if (isMusic != 0) { // 只把音乐添加到集合当中
                music.setId(id);
                music.setName(title);
                music.setSinger(artist);
                music.setDuration((int) duration);
                music.setSize(size);
                music.setPath(url);
                musics.add(music);
            }
        }
        return musics;
    }
}
